package com.djhu.es.core;
/**
 * Created by zw on 2017/12/28.
 */

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * <p>
 * ---------------------------------
 */


public class ResultListExtract<T> implements ResultExtractor<List<T> >{
    private static Logger logger= LoggerFactory.getLogger(ResultExtractor.class.getName());

    private RowMapper<T> rowMapper;
    private Client client;
    private int rowSize ;
    private int default_time = 300;
    public ResultListExtract(RowMapper<T> rowMapper,Client client) {
        this.rowMapper = rowMapper;
        rowSize = 0;
        this.client = client;
    }

    public ResultListExtract() {

    }

    @Override
    public List<T> extractData(Object object) throws Exception {
        List<T> results= new ArrayList<>();
        if (object instanceof Collection){
            Collection collection = (Collection)object;
            for (Object obj:collection){
                results.add(rowMapper.mapRow(object,rowSize++));
            }
        }else if (object instanceof SearchResponse){
            SearchResponse searchResponse =(SearchResponse)object;
            do {
                for (SearchHit hit:searchResponse.getHits().getHits()) {
                    results.add(rowMapper.mapRow(hit.getSourceAsMap(), rowSize++));
                }
                searchResponse = client.prepareSearchScroll(searchResponse.getScrollId()).setScroll(new TimeValue(default_time, TimeUnit.SECONDS)).execute().actionGet();
            }while (searchResponse.getHits().getHits().length != 0);
        }
        return results;
    }
}